package com.example.spring_forum.controller;

import com.example.spring_forum.common.AppResult;
import com.example.spring_forum.common.ResultCode;
import com.example.spring_forum.config.AppConfig;
import com.example.spring_forum.exception.model.Article;
import com.example.spring_forum.exception.model.User;
import com.example.spring_forum.services.IArticleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "帖子接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Resource
    private IArticleService articleService;

    @ApiOperation("获取板块帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@ApiParam("板块id")@RequestParam(value = "boardId",required = false) Long boardId){

        List<Article> articles;

        if(boardId == null){
            //查询所有
            articles=articleService.selectAll();
        }else{
            //查询对应板块中所有帖子集合
            articles=articleService.selectByBoardId(boardId);
        }

         //判断查询结果是否为空
        if(articles == null){
            articles = new ArrayList<>();//保证返回的是空集合
        }
        //返回结果
        return  AppResult.success(articles);
    }

    @ApiOperation("发布帖子")
    @PostMapping("/create")
    public AppResult create (HttpServletRequest request,
                             @ApiParam("版块Id") @RequestParam("boardId") @NonNull Long boardId,
                             @ApiParam("帖子标题") @RequestParam("title") @NonNull String title,
                             @ApiParam("帖子正文") @RequestParam("content") @NonNull String content) {
        // 获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.SESSION_USER_KRY);
        // 校验用户状态
        if (user.getState() == 1) {
            // 用户已禁言, 返回提示
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 构造帖子对象
        Article article = new Article();
        article.setUserId(user.getId()); // 当前登录用户就是作者
        article.setBoardId(boardId); // 版块Id
        article.setTitle(title); // 帖子标题
        article.setContent(content); // 帖子正文
        // 调用Service
        articleService.create(article);
        // 返回结果
        return AppResult.success("帖子发布成功");
    }

    @ApiOperation("获取帖子详情")
    @GetMapping("/getById")
    public AppResult<Article> getDetails (HttpServletRequest request,
                                          @ApiParam("帖子Id") @RequestParam("id") @NonNull Long id) {
        // 调用Service
        Article article = articleService.selectById(id);
        // 校验
        if (article == null) {
            // 返回提示
            return AppResult.failed("帖子不存在");
        }
         //更新访问次数（更新了数据库里的）
        articleService.updateVisitCount(article.getId());

        //返回之前更新返回对象的访问次数
        article.setVisitCount(article.getVisitCount()+1);

        //获取当前登录的用户信息
        HttpSession session=request.getSession(false);
        User user=(User)session.getAttribute(AppConfig.SESSION_USER_KRY);
        //判断是否是用户自己的帖子
        if(user.getId() == article.getUserId()){
            article.setOwn(true);
        }
        // 返回成功信息
        return AppResult.success(article);
    }
    @ApiOperation("编辑帖子")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam("帖子id") @RequestParam("id")@NonNull Long id,
                            @ApiParam("帖子title") @RequestParam("title")@NonNull String title,
                            @ApiParam("帖子content") @RequestParam("content")@NonNull String content){
        //从session中得到用户信息
        HttpSession session=request.getSession(false);
        User user=(User)session.getAttribute(AppConfig.SESSION_USER_KRY);
        //校验用户信息
        if(user.getState() == 1){
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);

        }
        //查询帖子信息
        Article article=articleService.selectById(id);
         //校验帖子是否存在
        if(article == null){
             return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        //检验当前登录用户是否是作者
        if(article.getUserId() != user.getId()){
            //返回提示信息
            return AppResult.failed("您不是帖子作者，无权修改");
        }

        if(article.getState() == 1){
            return AppResult.failed("帖子状态异常，请联系管理员");
        }

        articleService.modify(id,title,content);
        return AppResult.success("修改成功");
    }

    @ApiOperation("获取用户帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult getAllByUserId (HttpServletRequest request,
                                     @ApiParam("用户Id") @RequestParam(value = "userId", required = false) Long userId) {
        // 判断userId是否为空
        if (userId == null) {
            // 获取session对象
            HttpSession session = request.getSession(false);
            // 从session 中获取User对象
            User user = (User) session.getAttribute(AppConfig.SESSION_USER_KRY);
            // 设置UserId
            userId = user.getId();
        }
        // 调用Service
        List<Article> result = articleService.selectByUserId(userId);
        // 判断是否为null
        if (result == null) {
            result = new ArrayList<>();
        }
        // 返回结果
        return AppResult.success(result);
    }

}
